package com.itheima.controller;

import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 体检预约发送验证码
	 * 该方法用于向用户手机发送体检预约的验证码
	 *
	 * @param telephone 用户的电话号码，用于接收验证码
	 * @return 返回包含验证码的结果对象
	 */
	@PostMapping("/send4Order")
	public Result send4Order(String telephone) {
		// 生成并返回验证码，有效期为5分钟
		Integer validateCode = getValidateCodeWithExpireTime(4,
				RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone,
				5, TimeUnit.MINUTES);

		// 返回包含验证码的结果对象
		return new Result(true, String.valueOf(validateCode));
	}

	/**
	 * 用户登录发送验证码
	 *
	 * @param telephone
	 * @return
	 */
	@GetMapping("/send4Login")
	public Result send4Login(String telephone) {
		// 生成登录用的验证码，有效期5分钟
		Integer validateCode = getValidateCodeWithExpireTime(6,
				RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone,
				5, TimeUnit.MINUTES);

		// 返回生成的验证码
		return new Result(true, String.valueOf(validateCode));
	}

	public Integer getValidateCodeWithExpireTime(Integer codeLength, String key,
												 Integer expireTime, TimeUnit timeUnit) {
		// 随机生成长度为codeLength的数字验证码
		Integer validateCode = ValidateCodeUtils.generateValidateCode(codeLength);
		redisTemplate.opsForValue().set(key, validateCode, expireTime, timeUnit);

		return validateCode;
	}
}
